// // ******************************************************************
// //       /\ /|       @file       TranslationRecordRepository.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-03-01 20:03
// //    *(__\_\        @Copyright  Copyright (c) , 2025-02-23 10:02 Await
// // ******************************************************************

using AutomaticSubtitles.Service.DataAccess;
using AutomaticSubtitles.Service.DataAccess.Model;
using AutomaticSubtitles.Service.Domain.Translate;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace AutomaticSubtitles.Service.Infrastructure.Repositories;

public class TranslationRecordRepository(AutoDbContext context, IUnitOfWork unitOfWork, IStringLocalizer<SharedResource> localizer)
    : BaseRepository<AutoDbContext, Auto_TranslationRecord, string>(context, unitOfWork, localizer), ITranslationRecordRepository
{
    public async Task<(List<Auto_TranslationRecord> Records, long Total)> GetTranslationRecordsAsync(
        string? mediaId = null,
        string? mediaName = null,
        string? name = null,
        string? translatedLanguage = null,
        DateTime? startTime = null,
        DateTime? endTime = null,
        string? sortField = null,
        string? sortOrder = null,
        int pageSize = 20,
        int pageIndex = 1)
    {
        var query = Context.Set<Auto_TranslationRecord>()
            .Include(x => x.AutoMedia)
            .AsNoTracking()
            .Where(x => true);

        // 应用筛选条件
        if (!string.IsNullOrEmpty(mediaId))
            query = query.Where(x => x.MediaId == mediaId);

        if (!string.IsNullOrEmpty(mediaName))
            query = query.Where(x => x.AutoMedia.Name.Contains(mediaName));

        if (!string.IsNullOrEmpty(name))
            query = query.Where(x => x.Name.Contains(name));

        if (!string.IsNullOrEmpty(translatedLanguage))
            query = query.Where(x => x.TranslatedLanguage == translatedLanguage);

        if (startTime.HasValue)
            query = query.Where(x => x.CreateTime >= startTime.Value);

        if (endTime.HasValue)
            query = query.Where(x => x.CreateTime <= endTime.Value);

        // 获取总数
        var total = await query.LongCountAsync();

        // 应用排序
        if (!string.IsNullOrEmpty(sortField))
            query = sortField.ToLower() switch
            {
                "createtime" => sortOrder?.ToLower() == "desc"
                    ? query.OrderByDescending(x => x.CreateTime)
                    : query.OrderBy(x => x.CreateTime),
                "name" => sortOrder?.ToLower() == "desc"
                    ? query.OrderByDescending(x => x.Name)
                    : query.OrderBy(x => x.Name),
                "medianame" => sortOrder?.ToLower() == "desc"
                    ? query.OrderByDescending(x => x.AutoMedia.Name)
                    : query.OrderBy(x => x.AutoMedia.Name),
                _ => query.OrderByDescending(x => x.CreateTime)
            };
        else
            query = query.OrderByDescending(x => x.CreateTime);

        // 应用分页
        var records = await query
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        return (records, total);
    }

    public async Task<int> DeleteTranslationRecordsAsync(List<string> ids)
    {
        var records = await GetRecordsByIdsAsync(ids);
        if (!records.Any())
            return 0;

        Context.Set<Auto_TranslationRecord>().RemoveRange(records);
        await Context.SaveChangesAsync();
        return records.Count;
    }

    public async Task<List<Auto_TranslationRecord>> GetRecordsByIdsAsync(List<string> ids)
    {
        return await Context.Set<Auto_TranslationRecord>()
            .Where(x => ids.Contains(x.Id))
            .ToListAsync();
    }

    public async Task<string> AddTranslationRecordAsync(Auto_TranslationRecord record)
    {
        // 设置创建时间
        record.CreateTime = DateTime.Now;
        try
        {
            // 在添加记录前检查ID冲突
            var existingRecord = await Context.Set<Auto_TranslationRecord>()
                .AsNoTracking()
                .FirstOrDefaultAsync(x => x.Id == record.Id);

            if (existingRecord != null)
            {
                // ID冲突，生成新ID
                var newId = $"record_{DateTime.Now.Ticks}_{Guid.NewGuid():N}";
                record.SetId(newId);
            }

            // 如果包含媒体对象，检查媒体ID是否已存在
            if (record.AutoMedia != null)
            {
                var mediaId = record.AutoMedia.Id;
                var existingMedia = await Context.Set<Auto_Media>()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(x => x.Id == mediaId);

                if (existingMedia != null)
                {
                    // 媒体ID冲突检查
                    if (existingMedia.Path == record.AutoMedia.Path)
                    {
                        // 路径相同，使用现有媒体，避免重复添加
                        record.MediaId = existingMedia.Id;
                        record.AutoMedia = null; // 不添加新媒体
                    }
                    else
                    {
                        // 路径不同，生成新媒体ID
                        var newMediaId = $"media_{DateTime.Now.Ticks}_{Guid.NewGuid():N}";
                        record.AutoMedia.SetId(newMediaId);
                        record.MediaId = newMediaId;
                    }
                }
            }

            // 添加记录
            await Context.Set<Auto_TranslationRecord>().AddAsync(record);

            // 保存更改
            await Context.SaveChangesAsync();

            // 提交事务
            await UnitOfWork.CommitAsync();

            return record.Id;
        }
        catch (Exception)
        {
            // 其他错误，回滚事务
            await UnitOfWork.RollbackAsync();
            throw; // 重新抛出原始异常
        }
    }
}